<!--
 * 组织/职务 列表
 *
 * @author tqfeiyang
 * @since 2024-09-19
-->
<template>
    <a-form class="smart-query-form" v-privilege="'oa:notice:query'">
        <a-row class="smart-query-form-row">
          <a-form-item label="关键字" class="smart-query-form-item">
            <a-input style="width: 300px" v-model:value="queryForm.keywords" placeholder="请输入关键字" />
          </a-form-item>
          <a-form-item label="名称" class="smart-query-form-item">
            <a-input style="width: 300px" v-model:value="queryForm.name" placeholder="请输入名称" />
          </a-form-item>
          <a-form-item label="职级" class="smart-query-form-item">
            <a-input style="width: 300px" v-model:value="queryForm.level" placeholder="请输入职级" />
          </a-form-item>
          <a-form-item label="备注" class="smart-query-form-item">
            <a-input style="width: 300px" v-model:value="queryForm.remark" placeholder="请输入备注" />
          </a-form-item>
            <a-form-item class="smart-query-form-item smart-margin-left10">
                <a-button-group>
                    <a-button type="primary" @click="onQuerySubmit">
                        <template #icon>
                            <SearchOutlined />
                        </template>
                        查询
                    </a-button>
                    <a-button @click="onQueryReset">
                        <template #icon>
                            <ReloadOutlined />
                        </template>
                        重置
                    </a-button>
                </a-button-group>
            </a-form-item>
        </a-row>
    </a-form>

    <a-card size="small" :bordered="false">
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button type="primary" @click="addOrUpdate()">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>

                <a-button type="primary" danger @click="batchDelete" :disabled="!hasSelected">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>

                <a-button @click="showImportModal" type="primary">
                  <template #icon>
                    <ImportOutlined />
                  </template>
                  导入
                </a-button>

                <a-button @click="exportExcel" type="primary">
                  <template #icon>
                    <ExportOutlined />
                  </template>
                  导出
                </a-button>

            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="tableColumns" :refresh="getPositionPage" />
            </div>
        </a-row>

        <a-table
            rowKey="positionId"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="tableColumns"
            :data-source="tableData"
            :pagination="true"
            :loading="tableLoading"
            @change="onTableChange"
            size="small"
            bordered
        >
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button type="link" @click="addOrUpdate(record.positionId)" v-privilege="'oa:notice:update'">编辑</a-button>
                        <a-button type="link" @click="singleDelete(record)" v-privilege="'oa:notice:delete'" danger>删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
    </a-card>

  <PositionDrawer ref="positionDrawer" @reloadList="getPositionPage" />
  <PositionImportModal ref="positionImportModal" @refresh="getPositionPage" />
</template>

<script setup>
  import { reactive, ref, computed, onMounted, createVNode } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import _ from 'lodash';
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import PositionDrawer from './components/position-drawer.vue';
  import PositionImportModal from './components/position-import-modal.vue';
  import { positionApi } from '/@/api/business/organization/position-api';

  // -------------------- 查询 --------------------

  const tableData = ref([]);
  const tableTotal = ref(0);
  const tableLoading = ref(false);

  const tableColumns = ref([
    {
      title: '职务id',
      dataIndex: 'positionId',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '职级',
      dataIndex: 'level',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '排序',
      dataIndex: 'sort',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      sorter: (a, b) => {},
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 120,
    },
  ]);

  const queryFormState = {
    pageNum: 1,
    pageSize: PAGE_SIZE,
    orderBy: null,
    direction: null,
    keywords: undefined, //关键字
    name: undefined, //名称
    level: undefined, //职级
    remark: undefined, //备注
  };

  const queryForm = reactive({ ...queryFormState });

  onMounted(() => {
    getPositionPage();
  });

  function onQuerySubmit() {
    queryForm.pageNum = 1;
    getPositionPage();
  }

  function onQueryReset() {
    Object.assign(queryForm, queryFormState);
    getPositionPage();
  }

  function onTableChange(pagination, filters, sorter) {
    queryForm.orderBy = sorter.field;
    queryForm.direction = sorter.order;
    getPositionPage();
  }

  async function getPositionPage() {
    try {
      tableLoading.value = true;
      const result = await positionApi.getPositionPage(queryForm)
      tableData.value = result.data.list;
      tableTotal.value = result.data.total;
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      tableLoading.value = false;
    }
  }

  // -------------------- 多选 --------------------

  const selectedRowKeys = ref([]);
  const hasSelected = computed(() => selectedRowKeys.value.length > 0);

  let selectedRows = [];

  function onSelectChange(keyArray, selectRows) {
    selectedRowKeys.value = keyArray;
    selectedRows = selectRows;
  }

  // ----------------- 新建/编辑 ------------------

  const positionDrawer = ref();

  function addOrUpdate(positionId) {
      positionDrawer.value.showModal(positionId);
  }

  // -------------------- 删除 --------------------

  function singleDelete(record) {
    confirmDelete([record]);
  }

  function batchDelete() {
    confirmDelete(selectedRows);
  }

  function confirmDelete(rows) {
    const names = rows.map((e) => e.name);
    Modal.confirm({
      title: '确定要删除如下数据吗?',
      icon: createVNode(ExclamationCircleOutlined),
      content: _.join(names, '、'),
      okText: '删除',
      okType: 'danger',
      onOk() {
        const positionIds = rows.map((e) => e.positionId);
        batchDeletePositions(positionIds);
        selectedRows = [];
        selectedRowKeys.value = [];
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function batchDeletePositions(positionIds) {
    try {
      SmartLoading.show();
      await positionApi.batchDeletePositions(positionIds);
      message.success('删除成功!');
      getPositionPage();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

// ----------------- 导入Excel ------------------

const positionImportModal = ref();

function showImportModal() {
  positionImportModal.value.showModal();
}

async function exportExcel() {
  await positionApi.exportPositionsToExcel();
}

</script>

<style lang="less" scoped>
</style>
